package com.wenwen.social.controller;

import com.wenwen.social.application.FollowApplication;
import com.wenwen.social.application.dto.*;
import com.wenwen.social.common.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.List;

import static com.wenwen.social.constant.errorcode.CommonErrorConstant.*;

@RestController
public class FollowController extends BaseController{
	@Autowired
	private FollowApplication followApplication;

	/**
	 * 我的粉丝查询
	 * http://localhost:8080/fans?pageNum=1&pageSize=10
	 * @param pageRequest
	 * @return
	 */
	@GetMapping("/fans")
	public PageResult<FansDTO> queryFans(@Validated PageRequest pageRequest){
		UserDTO currLoginUser = getCurrLoginUser();
		if(currLoginUser == null) {
			throw new ServiceException(USER_NOT_LOGIN_CODE,USER_NOT_LOGIN_MSG);
		}
		if(currLoginUser.getId() == null){
			throw new ServiceException(USER_NOT_EXIST_CODE,USER_NOT_EXIST_MSG);
		}
		PageResult<FansDTO> fansDTOPageResult = followApplication.queryFans(currLoginUser.getId(), pageRequest);
		return fansDTOPageResult;
	}

	/**
	 * 我关注的人
	 * http://localhost:8080/followings?pageNum=1&pageSize=10
	 * @param pageRequest
	 * @return
	 */
	@GetMapping("/followings")
	public PageResult<FollowingsDTO> queryFollowings(@Validated PageRequest pageRequest){
		UserDTO currLoginUser = getCurrLoginUser();
		if(currLoginUser == null) {
			throw new ServiceException(USER_NOT_LOGIN_CODE,USER_NOT_LOGIN_MSG);
		}
		if(currLoginUser.getId() == null){
			throw new ServiceException(USER_NOT_EXIST_CODE,USER_NOT_EXIST_MSG);
		}
		PageResult<FollowingsDTO> fansDTOPageResult = followApplication.queryFollowings(currLoginUser.getId(), pageRequest);
		return fansDTOPageResult;
	}

	/**
	 * http://localhost:8080/follow
	 * [3,4]
	 * @param list
	 * @return  1:删除成功  0:没有删除的记录
	 */
	@PostMapping("/follow")
	public Long addFollowings(@RequestBody List<Long> list){
		if(list.isEmpty()) throw new ServiceException(PARAMETER_ILLGAL_CODE,"关注列表不能为空");
		UserDTO currLoginUser = getCurrLoginUser();
		checkUser(currLoginUser);

		followApplication.follow(currLoginUser.getId(), list);
		return 1L;
	}



	@PutMapping("/unfollow")
	public Long unFollowings(@NotNull(message = "取消关注用户id不能为空")  Long fid){
		UserDTO currLoginUser = getCurrLoginUser();
		checkUser(currLoginUser);

		followApplication.unfollow(currLoginUser.getId(), fid);
		return 1L;
	}

	private void checkUser(UserDTO currLoginUser) {
		if(currLoginUser == null) {
			throw new ServiceException(USER_NOT_LOGIN_CODE,USER_NOT_LOGIN_MSG);
		}
		if(currLoginUser.getId() == null){
			throw new ServiceException(USER_NOT_EXIST_CODE,USER_NOT_EXIST_MSG);
		}
	}

}
